
#include "scope.h"
#include "hash_table.h"

#include <stdlib.h>
#include <string.h>

#define SCOPE_MAX 100

static int level=0;
static struct hash_table * scope[SCOPE_MAX] = {0};

int scope_enter()
{
	level++;
	if(level>=SCOPE_MAX) abort();
	scope[level] = hash_table_create(0,0);
	return level;
}

int scope_level()
{
	return level;
}

int scope_exit()
{
	hash_table_delete(scope[level]);
	level--;
	return level;
}

int scope_bind( char *name, struct symbol *s )
{
	if(!scope[0]) scope[0] = hash_table_create(0,0);

	if(hash_table_lookup(scope[level],name)) {
		return 0;
	} else {
		hash_table_insert(scope[level],name,s,(void**)0);
		return 1;
	}
}

struct symbol * scope_lookup( const char *name )
{
	int i;
	struct symbol *s;

	if(!scope[0]) scope[0] = hash_table_create(0,0);

	for(i=level;i>=0;i--) {
		s = hash_table_lookup(scope[i],name);
		if(s) return s;
	}
	return 0;
}
